package org.nt4b.schemadoc.webgui.service;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.Serializable;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.nt4b.schemadoc.core.dom.SchemaComments;
import org.nt4b.schemadoc.core.dom.Table;
import org.nt4b.schemadoc.core.in.XMLCommentsReader;
import org.nt4b.schemadoc.core.out.DocumentationOutputBuilder;
import org.nt4b.schemadoc.core.out.OutputBuilder;
import org.nt4b.schemadoc.core.out.SQLOutputBuilderFactory;
import org.nt4b.schemadoc.core.out.XMLOutputBuilder;
import org.nt4b.schemadoc.webgui.ConnectionConfiguration;
import org.nt4b.schemadoc.webgui.FileUploadBean;
import org.springframework.webflow.context.ExternalContext;
import org.springframework.webflow.execution.RequestContext;


public class ImportExportServiceImpl implements Serializable, ImportExportService {
    private static final long serialVersionUID = 5965843251376448805L;
    
    private final Logger logger = Logger.getLogger(ImportExportServiceImpl.class);
    
    private CommentsService commentsService;
    
    public ImportExportServiceImpl() {
    }
    
    public CommentsService getCommentsService() {
        return commentsService;
    }
    
    public void setCommentsService(final CommentsService commentsService) {
        this.commentsService = commentsService;
    }
    
    public void exportXML(final ConnectionConfiguration connectionConfiguration, final RequestContext context) throws Exception {
        logger.info("Export XML");
        System.out.println("Export XML");
        
        final OutputBuilder outputBuilder = new XMLOutputBuilder();
        export(connectionConfiguration, context, outputBuilder, "xml");
    }
    
    public void exportSQL(final ConnectionConfiguration connectionConfiguration, final RequestContext context) throws Exception {
        final String url = connectionConfiguration.getConnectionProperties().getUrl();
        final OutputBuilder outputBuilder = SQLOutputBuilderFactory.getDBOutputBuilder(url);
        export(connectionConfiguration, context, outputBuilder, "sql");
    }
    
    public void exportDoc(final ConnectionConfiguration connectionConfiguration, final RequestContext context) throws Exception {
        final OutputBuilder outputBuilder = new DocumentationOutputBuilder();
        export(connectionConfiguration, context, outputBuilder, "txt");
    }
    
    private void export(final ConnectionConfiguration connectionConfiguration, final RequestContext context, final OutputBuilder outputBuilder, final String fileSuffix) throws Exception {
        final List<Table> tables = commentsService.loadSchemaComments(connectionConfiguration);
        
        final String userName = connectionConfiguration.getConnectionProperties().getUsername();
        final SimpleDateFormat sdf = new SimpleDateFormat();
        final String dateString = sdf.format(new Date());
        final String fileName = "export_" + userName + "_" + dateString + "." + fileSuffix;
        
        final String outputString = outputBuilder.buildResult(tables);
        
        final ExternalContext externalContext = context.getExternalContext();
        final HttpServletResponse response = (HttpServletResponse) externalContext.getNativeResponse();
        
        response.setContentType("application/octet-stream");
        response.setContentLength(outputString.length());
        response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
        
        // stream PDF content here...
        final OutputStream out = response.getOutputStream();
        final PrintWriter writer = new PrintWriter(out, true);
        writer.write(outputString);
        writer.flush();
        
        externalContext.recordResponseComplete();
    }
    
    @Override
    public void upload(final ConnectionConfiguration connectionConfiguration, final FileUploadBean fileUploadBean) {
        System.out.println(fileUploadBean.getFile().getName());
        
        try {
            final InputStream in = fileUploadBean.getFile().getInputStream();
            
            final XMLCommentsReader reader = new XMLCommentsReader();
            final SchemaComments schemaComments = reader.readSchema(in);
            
            commentsService.saveSchemaComments(connectionConfiguration, schemaComments);
        } catch (final IOException e) {
            logger.error("Could not read file content", e);
        }
        
    }
    
}
